package com.zzzyh.forumsystemclient.services.impl;

import com.zzzyh.forumsystemclient.common.AppResult;
import com.zzzyh.forumsystemclient.common.ResultCode;
import com.zzzyh.forumsystemclient.dao.ArticleMapper;
import com.zzzyh.forumsystemclient.dao.UserMapper;
import com.zzzyh.forumsystemclient.exception.AppException;
import com.zzzyh.forumsystemclient.model.Article;
import com.zzzyh.forumsystemclient.model.PageRequest;
import com.zzzyh.forumsystemclient.model.PageResult;
import com.zzzyh.forumsystemclient.model.User;
import com.zzzyh.forumsystemclient.services.IArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl implements IArticleService {
    @Autowired
    private ArticleMapper  articleMapper;

    @Autowired
    private UserMapper  userMapper;
    @Override
    public PageResult<Article> getArticles(PageRequest pageRequest) {
        List<Article> articles = articleMapper.getArticles(pageRequest);
        articles.forEach(article -> {
            User user = userMapper.selectByPrimaryKey(article.getUserId());
            if ( user == null)
                throw  new AppException(AppResult.failed(ResultCode.FAILED_DB_ERROR));
            user.setPassword(null);
            user.setSalt(null);
            article.setUser(user);
        });
        return new PageResult<Article>(pageRequest.getCurrentPage(),pageRequest.getPageSize(),
                articleMapper.getArticleCount(),articles);
    }

    @Override
    public Long gerUserIdByArticleId(Long articleId) {
        return articleMapper.getUserIdByArticleId(articleId);
    }

    @Override
    public Article getArticleByArticleId(Long articleId) {
        return  articleMapper.selectByPrimaryKey(articleId);
    }

    @Override
    public void createArticle(Article article) {
        articleMapper.insertSelective(article);
    }

    @Override
    public void updateArticle(Article article) {
        articleMapper.updateByPrimaryKeySelective(article);
    }

    @Override
    public void deleteArticle(Long articleId) {
        articleMapper.deleteByPrimaryKey(articleId);
    }

    @Override
    public List<Article> getArticlesByUserId(Long userId) {
        List<Article> articles = articleMapper.getArticlesByUserId(userId);
        articles.forEach(article -> {
            User user = userMapper.selectByPrimaryKey(article.getUserId());
            if ( user == null)
                throw  new AppException(AppResult.failed(ResultCode.FAILED_DB_ERROR));
            user.setPassword(null);
            user.setSalt(null);
            article.setUser(user);
        });
        return articles;
    }

    @Override
    public List<Article> searchArticles(String keyword) {
        List<Article> articles = articleMapper.searchArticles(keyword);

        return articles.stream()
                .sorted((a1, a2) -> {
                    int score1 = calculateRelevanceScore(a1, keyword);
                    int score2 = calculateRelevanceScore(a2, keyword);
                    return Integer.compare(score2, score1); // 降序排列
                })
                .collect(Collectors.toList());
    }

    private int calculateRelevanceScore(Article article, String keyword) {
        int score = 0;

        if (article.getTitle() != null && article.getTitle().contains(keyword)) {
            score += 5; // 标题命中
        }

        if (article.getContent() != null) {
            long count = Arrays.stream(article.getContent().split("\\s+"))
                    .filter(word -> word.equalsIgnoreCase(keyword))
                    .count();
            score += count * 2; // 内容中每出现一次 +2 分
        }

        if (article.getRemark() != null && article.getRemark().contains(keyword)) {
            score += 1; // 简介命中
        }

        if (article.getUser() != null && article.getUser().getUsername() != null &&
                article.getUser().getUsername().contains(keyword)) {
            score += 3; // 用户名命中
        }

        // 可选：根据热度调整分数
        score += Math.min(article.getLikeCount(), 10);  // 最多加10分点赞
        score += Math.min(article.getVisitCount() / 10, 10); // 浏览量加成

        return score;
    }
}
